const userInfoService = require('../../data/userInfoService.js');
const util = require('../../utils/util.js');
const cryptoJs = require("../../utils/cryptoJs.js");
const globalData = getApp().globalData;

Page({
  data: {
    isLoaded: false,
    isDemoData: false,
    voidText: '正在初始化数据...',
    mainPwd: '',
    localJsonData: {}
  },
  //输入框
  inputInputBind: function(event) {
    this.data.mainPwd = event.detail.value;
  },
  pwdAuthBind: function(event) {
    const pwd = this.data.mainPwd;
    if (pwd == undefined || pwd == '') {
      util.showToast("请输入主密码！");
      return;
    }
    const localJsonData = this.data.localJsonData;

    const md5Pwd = cryptoJs.MD5Encrypt(pwd);
    if (localJsonData.userInfo.enPassword !== md5Pwd) {
      util.showToast("输入的主密码不正确，请重新输入！")
      return;
    }

    globalData.password = pwd;
    util.navigateBack();
  },
  onLoad: function(options) {
    const isDemoData = options.isDemoData === 'true';
    const isCloudLoad = options.isCloudLoad === 'true';
    const localJsonData = util.getStorageData(globalData.localJsonName);
    //判断是否跳转
    const judgeIsnavigate = () => {
      this.setData({
        isLoaded: true,
        isDemoData: isDemoData,
        localJsonData: localJsonData
      });
      if (globalData.authenPassword == '') //没开启指纹功能
        return;

      const checkOption = {
        success: (res) => {
          globalData.password = globalData.authenPassword;
          util.navigateBack();
        },
        authentFail: (err) => {
          if (err.errCode != 90008) { //认证时，90008：用户点击了取消
            util.showToast('指纹认证失败！');
          }
        }
      };
      util.checkIsSoterEnrolledInDevice(checkOption);
    }

    //不是demo数据；没有开启云存储
    if (isDemoData || !globalData.userInfo.isCloudSyn || isCloudLoad) {
      judgeIsnavigate()
      return;
    }

    //加载云数据：开启了云存储，或者第一本地使用
    userInfoService.mergeCloudLocalData(globalData, localJsonData.time).then(res => {
      const isDemoData = res.isDemoData;
      if (res.hasRetJsonData) {
        const cloudData = res.retJsonData;
        localJsonData.version = cloudData.version;
        localJsonData.time = cloudData.time;
        localJsonData.userInfo = cloudData.userInfo;
        localJsonData.category = cloudData.category;
        localJsonData.key = cloudData.key;
        localJsonData.version = cloudData.version;

        if (globalData.userInfo.enPassword != cloudData.userInfo.enPassword) { //云端修改了密码
          globalData.userInfo.enPassword = cloudData.userInfo.enPassword;
          globalData.authenPassword = '';
        }

        util.setStorageData(globalData.localJsonName, localJsonData);
        util.setStorageData(globalData.localConfigName, globalData);
      }
      judgeIsnavigate();
    }).catch(err => {
      console.error(err);

      this.setData({
        voidText: '数据初始化失败！'
      })
    });
  }
})